<?php


namespace App\Http\Controllers\Admin\Access;


use App\Response\Response;
use Illuminate\Http\Request;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Http\Controllers\BaseController;
//权限
class AccessController extends BaseController
{
    /**
     * @api {post} /access 添加权限
     *
     * @apiGroup 新权限模块
     *
     * @apiParam {string} access_name 权限名称。必须
     * @apiParam {int} menu_id 所属菜单id，必须
     * @apiParam {int} sort 排序号，ps：升序排列，页面类权限建议0，其它权限建议30000，不填默认30000
     * @apiParam {string} route_ids 关联的路由id，多个用英文逗号隔开，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function add(Request $request)
    {
        $param = $request->only('access_name', 'menu_id', 'sort', 'route_ids');
        $v = app('validator')->make($param,[
            'access_name' => 'required|string|min:2|max:16',
            'menu_id' => 'required|integer',
            'sort' => 'integer|min:0|max:65535',
            'route_ids' => 'required|string|max:1000',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        app('repo_access')->addOrEditAccess($param);
        return Response::sendData([]);
    }

    /**
     * @api {put} /access 编辑权限
     *
     * @apiGroup 新权限模块
     *
     * @apiParam {int} id 权限id。必须
     * @apiParam {string} access_name 权限名称。必须
     * @apiParam {int} menu_id 所属菜单id，必须
     * @apiParam {int} sort 排序号，ps：升序排列，页面类权限建议0，其它权限建议30000，不填默认30000
     * @apiParam {string} route_ids 关联的路由id，多个用英文逗号隔开，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function edit(Request $request)
    {
        $param = $request->only('id', 'access_name', 'menu_id', 'sort', 'route_ids');
        $v = app('validator')->make($param,[
            'id' => 'required|integer',
            'access_name' => 'required|string|min:2|max:16',
            'menu_id' => 'required|integer',
            'sort' => 'integer|min:0|max:65535',
            'route_ids' => 'required|string|max:1000',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        app('repo_access')->addOrEditAccess($param);
        return Response::sendData([]);
    }

    /**
     * @api {delete} /access 删除权限
     *
     * @apiGroup 新权限模块
     *
     * @apiParam {string} ids 权限id，多个用英文逗号隔开，必须
     *
     * @apiParam {string} ids 权限id，多个用英文逗号隔开
     *
     * @apiSuccessExample {json} Response-Example
     * {"code":200,"data":[],"message":""}
     */
    public function del(Request $request)
    {
        $param = $request->only('ids');
        $v = app('validator')->make($param,[
            'ids' => 'required',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $ids = explode(',', $param['ids']);

        $queryIds = app('model_access')->select('id')->whereIn('id', $ids)->pluck('id')->toArray();
        if (count($queryIds) != count($ids)) throw new BasicException(0, '权限id错误');

        DB::beginTransaction();
        try {

            app('repo_access')->delAccesses($ids);

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {get} /access 权限列表
     *
     * @apiGroup 新权限模块
     *
     * @apiParam {int} menu_id 菜单id，-1表示不限制，其它根据接口
     * @apiParam {string} access_name 权限名称（模糊搜索）
     * @apiParam {int} page 第几页，默认1
     * @apiParam {int} page_size 每页显示条数，1-100，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1, 权限id
    "name": "管理员新增", 权限名称
    "menu_id": 5, 所属菜单id
    "sort": 30000, 排序号
    "admin_id": 72,
    "created_at": "2021-10-15 16:50:33", 添加时间
    "routes": [ 包含的路由（展示的时候用uri拼接英文冒号再拼接method）：
    {
    "access_id": 1,
    "route_id": 8,
    "uri": "valiimg",
    "method": "put"
    }
    ],
    "menu_name": "管理员列表", 所属菜单名称
    "parent_id": 1, 父菜单id
    "admin_name": "wangyuanyuan" 操作人
    }
    ],
    "first_page_url": "http://qipaoadmin/access?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://qipaoadmin/access?page=1",
    "next_page_url": null,
    "path": "http://qipaoadmin/access",
    "per_page": 10,
    "prev_page_url": null,
    "to": 7,
    "total": 7
    },
    "message": ""
    }
     */
    public function list(Request $request)
    {
        $param = $request->only('menu_id', 'access_name', 'page', 'page_size');
        $v = app('validator')->make($param,[
            'menu_id' => 'integer',
            'access_name' => 'string|max:20',
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1|max:100',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $menuId = $param['menu_id'] ?? -1;
        $accessName = $param['access_name'] ?? '';
        $pageSize = $param['page_size'] ?? 10;

        $where = [];
        if ($menuId != -1) {
            $where[] = ['menu_id', '=', $menuId];
        }
        if ($accessName) {
            $where[] = ['name', 'like', "%$accessName%"];
        }

        $list = app('model_access')
            ->select('id', 'name', 'menu_id', 'sort', 'admin_id', 'created_at')
            ->where($where)
            ->paginate($pageSize)->toArray();

        $accessIds = array_column($list['data'], 'id');
        $menuIds = array_column($list['data'], 'menu_id');
        $adminIds = array_column($list['data'], 'admin_id');

        $routesWithAccessIdMap = app('model_route')->getRoutesWithAccessIdMap($accessIds);
        $menus = app('model_menu')
            ->select('menu_name', 'menu_id', 'parent_id')
            ->whereIn('menu_id', $menuIds)
            ->get()->toArray();
        $menus = array_column($menus, null, 'menu_id');
        $admins = app('model_admin')->select('admin_name', 'admin_id')->whereIn('admin_id', $adminIds)->pluck('admin_name', 'admin_id')->toArray();

        foreach ($list['data'] as &$v) {
            $v['routes'] = $routesWithAccessIdMap[$v['id']] ?? '';
            $v['menu_name'] = $menus[$v['menu_id']]['menu_name'] ?? '';
            $v['parent_id'] = $menus[$v['menu_id']]['parent_id'] ?? 0;
            $v['admin_name'] = $admins[$v['admin_id']] ?? '';
        }
        return Response::sendData($list);
    }
}
